import java.io.BufferedReader;
import java.io.File;
//import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Loader {
	
	private final static File m_dataFile = new File(Driver.FILE_NAME);
	
	public static void Load() throws NumberFormatException, IOException{
		int diskBaseLocation = 0, sizeOnDisk = 0, currentAddress = 0;
		BufferedReader br = new BufferedReader(new FileReader(m_dataFile));
		String line = "";
		Pattern jobLine = Pattern.compile("^// ?JOB( *)([0-9A-F].?) ([0-9A-F].?) ?([0-9A-F].?)$");
		Matcher jobMatcher = jobLine.matcher(line);
		Pattern insLine = Pattern.compile("^0x([0-9A-F]{8})");
		Matcher insMatcher = insLine.matcher(line);
		Pattern datLine = Pattern.compile(("^// ?Data( *)([0-9A-F].?) ([0-9A-F].?) ([0-9A-F].?)$"));
		Matcher datMatcher = datLine.matcher(line);
		Pattern endLine = Pattern.compile("^// ?END$");
		Matcher endMatcher = endLine.matcher(line);
		int jobNumber = 0, jobLength = 0, jobPriority = 0;
		int inputBufferSize = 0, outputBufferSize = 0, tempBufferSize = 0;
		while((line = br.readLine()) != null){
			jobMatcher.reset(line);
			insMatcher.reset(line);
			datMatcher.reset(line);
			endMatcher.reset(line);
			
			if(jobMatcher.matches()){
				jobNumber = Integer.parseInt(jobMatcher.group(2), 16);
				jobLength = Integer.parseInt(jobMatcher.group(3), 16);
				jobPriority = Integer.parseInt(jobMatcher.group(4), 16);
			}
			else if(datMatcher.matches()){
				inputBufferSize = Integer.parseInt(datMatcher.group(2), 16);
				outputBufferSize = Integer.parseInt(datMatcher.group(3), 16);
				tempBufferSize = Integer.parseInt(datMatcher.group(4), 16);
			}
			else if(insMatcher.matches()){
				Disk.write(currentAddress, insMatcher.group(1));
				currentAddress++;
				sizeOnDisk++;
			}
			else if(endMatcher.matches()){
				Jobs.allJobs.add(new Process(jobNumber,
											 jobLength,
											 jobPriority,
											 inputBufferSize,
											 outputBufferSize,
											 tempBufferSize,
											 diskBaseLocation,
											 sizeOnDisk));
                diskBaseLocation += sizeOnDisk;
                sizeOnDisk = 0;
                Jobs.allJobs.get(Jobs.allJobs.size() - 1).setTime(true, true); //Set Start Wait Time.
                Jobs.allJobs.get(Jobs.allJobs.size() - 1).state = Process.State.NEW;
			}
		}
	}
}
